#include "RobotHMHModify.h"
#include "stage.h"

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#include <ctime>
#include <cstdlib>

using namespace std;

RobotHMHModify::RobotHMHModify(Model *model):RobotBase(model)
{
    CurrentTime = 0;
    SizeRecord = 0;

    StimulateOnlyPhase = RefracPhase;

    srand(time(0));
}

RobotHMHModify::~RobotHMHModify()
{
}

void RobotHMHModify::Estimate()
{
    if( CurrentTime < MaxTime)
    {
        CurrentTime++;
        if( CurrentTime > StimulateOnlyPhase && IsBroadCast())
        {
            GroupSize = SizeRecord + 1;
            SizeRecord = 0;
            StimulateOnlyPhase = MaxTime;
            BroadCast();
            if(verbose)
                printf("===============Robot: %d Emit a signal GroupSize %d\n", id, GroupSize);
        }
    }
    else 
    {
        GroupSize = SizeRecord + 1;
        SizeRecord = 0;
        StimulateOnlyPhase = MaxTime;
        BroadCast();
        if(verbose)
            printf("===============Robot: %d Emit a signal GroupSize %d\n", id, GroupSize);
    }

}// end DoLoop()

void RobotHMHModify::MessageReceive(WifiMessageBase* mesg)
{
    if(verbose)
        printf("Robot: %d Recive a message SizeRecord: %d\n", id, SizeRecord);

    if( CurrentTime <= RefracPhase)
        return;

    StimulateOnlyPhase = StimulateOnlyPhase - Dec;
    if( StimulateOnlyPhase < RefracPhase)
        StimulateOnlyPhase = RefracPhase;

    BroadCast();
    SizeRecord++;
}

// Broadcast a message
void RobotHMHModify::BroadCast()
{
    if(verbose)
        printf("Robot: %d BroadCast a signal StimulateOnlyPhase: %d CurrentTime: %d\n", id, StimulateOnlyPhase, CurrentTime);
    CurrentTime = 0;
    //printf("Robot %d Broadcast \n", id);

    WifiMessageBase * base_ptr = new WifiMessageBase;
    wifi->comm.SendBroadcastMessage( base_ptr );
}

// Whether or not to broadcast a signal
bool RobotHMHModify::IsBroadCast()
{
    if( rand()%1000 < EmitProbability )
        return true;
    else
        return false;
}
